from django.http import JsonResponse
from lib.common import AbstractHandler, get_api_result, al_text
from apps.student.share import app_logger
from services.datamodel.absorbed.models import (mm_Note, mm_ShareParameter, mm_NoteMessage, mm_NoteRanking, mm_AllData,
                                                mm_FamousSentences, mm_NoteServersMessage, mm_NoteBanner,
                                                mm_Plan, mm_PlanCourse, mm_PlanStage, mm_PlanStageCourse,
                                                mm_PlanJoinInfo, mm_PlanClockInInfo)
from services.datamodel.student.models import mm_Student
from django.core.cache import cache
from datetime import datetime, date, timedelta
from django.db.models import Sum, Count, Q, F, Min, Max
from django.db import transaction
import json
import requests


class AbsorbedHandler(AbstractHandler):
    def __init__(self):
        AbstractHandler.__init__(self, app_logger)
        self.app_logger = app_logger
        self.METHOD_TAB = {
            'POST': {
                'my': self.my,
                'del_my_note': self.del_my_note,
                'add_message': self.add_message,
                'record_duration': self.record_duration,
                'add_note': self.add_note,
                'like': self.like,
                'number_action': self.number_action,
                'create_QRCode': self.create_QRCode,
                'note_share': self.note_share,
                'get_identity': self.get_identity,
                'add_message_like': self.add_message_like,
                'record_click': self.record_click,
                'add_task': self.add_task,
                'join_plan': self.join_plan,
                'send_duration': self.send_duration,
            },
            'GET': {
                'get_my_note': self.get_my_note,
                'note_list': self.note_list,
                'note_detail': self.note_detail,
                'my_data': self.my_data,
                'ranking': self.ranking,
                'my_ranking': self.my_ranking,
                'note_message': self.note_message,
                'unread_message': self.unread_message,
                'get_unread_message': self.get_unread_message,
                'get_sharedata': self.get_sharedata,
                'get_FamousSentences': self.get_FamousSentences,
                'get_datas': self.get_datas,
                'get_banner': self.get_banner,
                'get_ongoing_plan': self.get_ongoing_plan,
                'get_hot_plan_list': self.get_hot_plan_list,
                'get_stage_detail': self.get_stage_detail,
                'get_task_list': self.get_task_list,
                'get_plan_detail': self.get_plan_detail,
                'get_stage_detail_simplify': self.get_stage_detail_simplify,
                'get_my_plan_list': self.get_my_plan_list,
                'get_my_task_list': self.get_my_task_list,
            }
        }

    def my(self, request):
        img = request.POST.get('img', '')
        nickname = request.POST.get('nickname', '')
        user_id = request.session.get('studentid')
        mm_Student.filter(id=user_id).update(avatar=img, nick_name=nickname)
        return self.success()

    def get_my_note(self, request):
        page = request.GET.get('page', 1)
        status = request.GET.get('status', 0)
        user_id = request.session.get('studentid')
        res = mm_Note.get_list(page=page, user_id=user_id, status=status, like_u=user_id)
        return self.success(res)

    def del_my_note(self, request):
        id = request.POST.get('id', 0)
        user_id = request.session.get('studentid')
        mm_Note.filter(id=id, student_id=user_id).update(status=2)
        return self.success()

    def note_list(self, request):
        user_ip = request.META.get('REMOTE_ADDR')
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            user_ip = x_forwarded_for.split(',')[0]
        page = request.GET.get('page', 1)
        types = request.GET.get('types', 0)
        user_id = request.session.get('studentid')
        if int(types) == 1:
            m_ip = cache.get(user_ip+"m")
            if not m_ip:
                cache.set(user_ip+"m", 1, mm_AllData.rest_of_day())
                mm_AllData.update_all_num(num=7)
        res = mm_Note.get_list(page=page, types=types, status=0, like_u=user_id)
        ip = cache.get(user_ip)
        if not ip:
            cache.set(user_ip, 1, mm_AllData.rest_of_day())
            mm_AllData.update_all_num(num=12)
        # 记录次日登入用户数
        if user_id:
            today = str(date.today())+"-a"
            user_arr = cache.get(today)
            if not user_arr:
                cache.set(today, json.dumps([user_id]), None)
            else:
                user_list = json.loads(user_arr)
                user_list.append(user_id)
                cache.set(today, json.dumps(user_list), None)
        return self.success(res)

    def note_detail(self, request):
        id = request.GET.get('id', 0)
        res = mm_Note.filter(id=id).values("content", "created_at", "like", "share", "message", "private", "status",
                                           "duration", "student__nick_name", "student__id", "id", "student__avatar",
                                           "imgs", "student__title", "types").first()
        user_id = request.session.get('studentid')
        like_u = mm_NoteMessage.get_or_default(note_id=id, student_id=user_id, types=1, pid=0)
        if like_u:
            res['is_like'] = 1
            res['like_status'] = like_u.status
        else:
            res['is_like'] = 0
        return self.success(res)

    def note_message(self, request):
        page = request.GET.get('page', 1)
        id = request.GET.get('id', 0)
        like = request.GET.get('like', 0)
        times = request.GET.get('times', 0)
        user_id = request.session.get('studentid')
        res = mm_NoteMessage.get_list(page=page, note_id=id, like=like, times=times, uid=user_id)
        return self.success(res)

    def add_message(self, request):
        id = request.POST.get('id', 0)
        content = request.POST.get('content', '')
        user_id = request.session.get('studentid')
        pid = request.POST.get('pid', 0)
        result = al_text(content)
        if result == "block":
            return self.error("请文明评论!")
        userObj = mm_Student.get_or_default(id=user_id)
        if userObj.status in [2, 3]:
            if userObj.status == 3:
                return self.error("发送失败")
            if userObj.status == 2:
                user_status = cache.get('user_status_id'+str(user_id))
                if user_status:
                    return self.error("发送失败")
                else:
                    mm_Student.filter(id=user_id).update(status=1)
        mm_NoteMessage.create(note_id=id, content=content, student_id=user_id, pid=pid)
        mm_AllData.update_all_num(num=1)  # 评论数更新
        # 针对评论点赞累加
        noteObi = mm_Note.get_or_default(id=id)
        noteObi.message = noteObi.message + 1
        noteObi.save()
        mess_user = cache.get("message_user_"+str(noteObi.student_id))
        if mess_user:
            cache.incr("message_user_"+str(noteObi.student_id))
        else:
            cache.set("message_user_"+str(noteObi.student_id), 1, None)
        return self.success()

    def my_data(self, request):
        user_id = request.session.get('studentid')
        res = mm_NoteRanking.get_user_data(user_id=user_id)
        return self.success(res)

    def my_ranking(self, request):
        today = date.today()
        user_id = request.session.get('studentid')
        types = request.GET.get('types', 0)
        if int(types) == 0:
            times = [str(today) + " 00:00:00", str(today) + " 23:59:59"]
        if int(types) == 1:
            today = datetime.strptime(str(today), "%Y-%m-%d")
            monday = datetime.strftime(today - timedelta(today.weekday()), "%Y-%m-%d")
            monday_ = datetime.strptime(monday, "%Y-%m-%d")
            sunday = datetime.strftime(monday_ + timedelta(monday_.weekday() + 6), "%Y-%m-%d")
            times = [str(monday) + " 00:00:00", str(sunday) + " 23:59:59"]
        res = mm_NoteRanking.get_my_ranking(times=times, user_id=user_id)
        return self.success(res)

    def ranking(self, request):
        types = request.GET.get('types', 1)
        times = []
        today = date.today()
        if int(types) == 1:
            times = [str(today)+" 00:00:00", str(today)+" 23:59:59"]
        if int(types) == 2:
            today = datetime.strptime(str(today), "%Y-%m-%d")
            monday = datetime.strftime(today - timedelta(today.weekday()), "%Y-%m-%d")
            monday_ = datetime.strptime(monday, "%Y-%m-%d")
            sunday = datetime.strftime(monday_ + timedelta(monday_.weekday() + 6), "%Y-%m-%d")
            times = [str(monday)+" 00:00:00", str(sunday)+" 23:59:59"]
        res = mm_NoteRanking.get_ranking(times=times)
        user_ip = request.META.get('REMOTE_ADDR')
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            user_ip = x_forwarded_for.split(',')[0]
        m_ip = cache.get(user_ip+"c")
        if not m_ip:
            cache.set(user_ip+"c", 1, mm_AllData.rest_of_day())
            mm_AllData.update_all_num(num=6)
        return self.success(res)

    def record_duration(self, request):
        user_id = request.session.get('studentid')
        duration = request.POST.get('duration', 0)
        res = mm_Note.create(duration=duration, status=2, student_id=user_id)
        noterObj = mm_NoteRanking.get_or_default(day=date.today(), student_id=user_id)
        if not noterObj:
            mm_NoteRanking.create(duration=duration, student_id=user_id)
        else:
            noterObj.duration = noterObj.duration + int(duration)
            noterObj.save()
        mm_AllData.update_all_num(num=4)  # 专注次数
        #  专注人数---一人一天算一次
        user = cache.get('number_num_'+str(user_id))
        if not user:
            mm_AllData.update_all_num(num=5)
            cache.set('number_num_'+str(user_id), 1, mm_AllData.rest_of_day())
        return self.success(res.id)

    def add_note(self, request):
        content = request.POST.get('content', '')
        imgs = request.POST.get('imgs', '')
        id = request.POST.get('id', 0)
        private = request.POST.get('private', 0)
        user_id = request.session.get('studentid')
        types = request.POST.get('types', 0)
        result = al_text(content)
        if result == "block":
            return self.error("请文明发布,内容中含有违禁词!")
        userObj = mm_Student.get_or_default(id=user_id)
        if userObj.status in [2, 3]:
            if userObj.status == 3:
                return self.error("发送失败")
            if userObj.status == 2:
                user_status = cache.get('user_status_id'+str(user_id))
                if user_status:
                    return self.error("发送失败")
                else:
                    mm_Student.filter(id=user_id).update(status=1)
        noteObj = mm_Note.get_or_default(id=id)
        mm_AllData.update_all_num(num=3)
        if noteObj:
            noteObj.content = content
            noteObj.imgs = imgs
            noteObj.status = private
            noteObj.types = types
            noteObj.created_at = datetime.now()
            noteObj.save()
            return self.success(id)
        res = mm_Note.create(content=content, imgs=imgs, status=private, student_id=user_id, types=types)
        return self.success(res.id)

    def like(self, request):
        id = request.POST.get('id', 0)
        status = request.POST.get('status', 0)
        user_id = request.session.get('studentid')
        noteObi = mm_Note.get_or_default(id=id)
        obj = mm_NoteMessage.get_or_default(note_id=id, student_id=user_id, types=1, pid=0)
        if int(status) == 0:
            if not obj:
                mess_user = cache.get("message_user_"+str(noteObi.student_id))
                if mess_user:
                    cache.incr("message_user_"+str(noteObi.student_id))
                else:
                    cache.set("message_user_"+str(noteObi.student_id), 1, None)
                mm_NoteMessage.create(note_id=id, student_id=user_id, types=1)
            mm_AllData.update_all_num(num=2)  # 更新点赞累计数
            # 针对评论点赞累加
            if obj:
                obj.status = 1
                obj.save()
            noteObi.like = noteObi.like + 1
            noteObi.save()
        if int(status) == 1:
            obj.status = 3
            obj.save()
            noteObi.like = noteObi.like - 1
            noteObi.save()
        return self.success()

    def unread_message(self, request):
        user_id = request.session.get('studentid')
        mess_user = cache.get("message_user_"+str(user_id))
        # count = mm_NoteMessage.filter(status=0, note__student_id=user_id).count()
        return self.success(mess_user)

    def get_unread_message(self, request):
        page = request.GET.get('page', 1)
        user_id = request.session.get('studentid')
        res = mm_NoteMessage.get_unread_message(user_id=user_id, page=page)
        cache.set("message_user_"+str(user_id), 0)
        return self.success(res)

    def number_action(self, request):
        types = request.POST.get('types', 0)
        id = request.POST.get('id', 0)
        user_id = request.session.get('studentid')
        if int(types) == 10:
            user = cache.get('haibao_num_'+str(user_id)+str(id))
            if user:
                return self.success()
            cache.set('haibao_num_'+str(user_id)+str(id), 1, mm_AllData.rest_of_day())
        mm_AllData.update_all_num(num=types)
        return self.success()

    def create_QRCode(self, request):
        import base64
        path = request.POST.get('path', 0)
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
            "wx3af648c742d8be80", "37829be2b13040fcc425b4dfd667092f"
        )
        retObj = get_api_result(url)
        if retObj.get('errcode'):
            self.app_logger.error(str(retObj))
            return self.error("微信服务器错误")
        access_token = retObj.get('access_token', None)
        post_url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={}".format(access_token)
        QRcode = requests.post(url=post_url, data=json.dumps({"path": path, "width": 50}))
        b64encode = base64.b64encode(QRcode.content)
        s = b64encode.decode()
        b64_encode = 'data:image/jpeg;base64,%s' % s
        return self.success(b64_encode)

    def get_sharedata(self, request):
        res = mm_ShareParameter.filter(status=0).values()
        return self.success(list(res))

    def get_FamousSentences(self, request):
        res = mm_FamousSentences.values().order_by('?').first()
        return self.success(res)

    def note_share(self, request):
        id = request.POST.get('id', 0)
        user_id = request.session.get('studentid')
        user = cache.get('share_num_'+str(user_id)+str(id))
        mm_AllData.update_all_num(num=14)  # 这是笔记转发，每人无线次数
        if user:
            return self.success()
        noteObj = mm_Note.get_or_default(id=id)
        if noteObj:
            #  分享人数---一人一天算一次
            if not user:
                noteObj.share = noteObj.share + 1
                noteObj.save()
                cache.set('share_num_'+str(user_id)+str(id), 1, mm_AllData.rest_of_day())
        return self.success()

    def get_identity(self, request):
        user_id = request.session.get('studentid')
        res = mm_Student.filter(id=user_id).values('identity').first()
        return self.success(res['identity'])

    def add_message_like(self, request):
        """
        给评论点赞
        :param request:
        :return:
        """
        id = request.POST.get('id', 0)
        note_id = request.POST.get('note_id', 0)
        status = request.POST.get('status', 0)
        user_id = request.session.get('studentid')
        noteMObi = mm_NoteMessage.get_or_default(id=id)
        obj = mm_NoteMessage.get_or_default(note_id=note_id, student_id=user_id, types=1, pid=id)
        if int(status) == 0:
            if not obj:
                mess_user = cache.get("message_user_"+str(noteMObi.student_id))
                if mess_user:
                    cache.incr("message_user_"+str(noteMObi.student_id))
                else:
                    cache.set("message_user_"+str(noteMObi.student_id), 1, None)
                mm_NoteMessage.create(note_id=note_id, student_id=user_id, types=1, pid=id)
            mm_AllData.update_all_num(num=2)  # 更新点赞累计数
            # 针对评论点赞累加
            if obj:
                obj.status = 1
                obj.save()
            noteMObi.like = noteMObi.like + 1
            noteMObi.save()
        if int(status) == 1:
            obj.status = 3
            obj.save()
            noteMObi.like = noteMObi.like - 1
            noteMObi.save()
        return self.success()

    def record_click(self, request):
        today = str(date.today())
        id = request.POST.get('id', 0)
        res = cache.get(today+str(id))
        if res:
            cache.incr(today+str(id), 1)
        else:
            cache.set(today+str(id), 1, None)
        num = cache.get(today+str(id))
        resObj = mm_NoteServersMessage.get_or_default(id=id)
        resObj.today_clicksum = num
        resObj.click_sum = resObj.click_sum + 1
        resObj.save()
        return self.success()

    def get_banner(self, request):
        res = mm_NoteBanner.filter(status=0).values().order_by("-sort")
        return self.success(list(res))

    def get_datas(self, request):
        users = mm_Student.filter(source=13).count()
        count = mm_Note.count()
        return self.success({'users': users, 'count': count})

    def get_ongoing_plan(self, request):
        now = date.today()
        user_id = request.session.get('studentid')
        joinInfo = mm_PlanJoinInfo.filter(plan__status=mm_Plan.on_line_status, student_id=user_id, plan_stage__start_day__lt=now, plan_stage__end_day__gt=now) \
        .annotate(plan_title=F('plan__title'), course_title=F('plan_stage_course__plan_course__title')) \
        .values('plan_id', 'plan_stage_id', 'student_id', 'plan_title', 'duration', 'course_title')
        for ind in range(len(joinInfo)):
            clockInInfo = mm_PlanClockInInfo.filter(plan_stage_id=joinInfo[ind]['plan_stage_id'], student_id=joinInfo[ind]['student_id'])
            joinInfo[ind]['clock_in'] = clockInInfo.count()
            joinInfo[ind]['before_clock_in'] = clockInInfo.filter(plan_stage_course__day__lt=now).count()
            joinInfo[ind]['replenish_clock_in'] = clockInInfo.filter(types=mm_PlanClockInInfo.replenish_type).count()
            joinInfo[ind]['day_num'] = mm_PlanStageCourse.filter(plan_stage_id=joinInfo[ind]['plan_stage_id'], day__lt=now).count()
            joinInfo[ind]['task_duration'] = clockInInfo.aggregate(note_duration_sum=Sum('note__duration'))['note_duration_sum']
            joinInfo[ind]['cumulative_duration'] = joinInfo[ind]['duration'] + (0 if joinInfo[ind]['task_duration'] is None else joinInfo[ind]['task_duration'])
            joinInfo[ind]['forgot_clock_in'] = joinInfo[ind]['day_num'] - joinInfo[ind]['before_clock_in']
        return self.success(list(joinInfo))

    def get_hot_plan_list(self, request):
        user_id = request.session.get('studentid')
        now = date.today()
        end_date = now+timedelta(days=7)
        res = mm_PlanStage.filter(plan__status=mm_Plan.on_line_status, start_day__gt=now, start_day__lt=end_date) \
            .annotate(join_num=Count("plan_join_info_ps__id", distinct=True)) \
            .annotate(plan_stage_id=F('id'), title=F('plan__title'), img=F('plan__img'), virtual_num=F('plan__virtual_num'), original_price=F('plan__original_price'), price=F('plan__price')) \
            .values('plan_stage_id', 'start_day', 'title', 'img', 'virtual_num', 'join_num', 'original_price', 'price')
        for ind in range(len(res)):
            planJoinInfo = mm_PlanJoinInfo.filter(plan_stage_id=res[ind]['plan_stage_id'], student_id=user_id).first()
            res[ind]['join_status'] = mm_PlanJoinInfo.not_join_status if planJoinInfo is None else mm_PlanJoinInfo.is_join_status
            res[ind]['start_status'] = mm_PlanStage.stage_status_running if date.today() >= res[ind]['start_day'] else mm_PlanStage.stage_status_unstart
        return self.success(list(res))

    def get_stage_detail(self, request):
        plan_stage_id = request.GET.get('plan_stage_id')
        day = request.GET.get('day')
        if day:
            day = datetime.strptime(day, '%Y-%m-%d').date()
        user_id = request.session.get('studentid')
        res = {}
        if not plan_stage_id:
            return self.success(res)
        plan_stage = mm_PlanStage.get(id=plan_stage_id, plan__status=mm_Plan.on_line_status)
        if plan_stage is None:
            return self.success(res)
        now = date.today()
        plan_stage_course = plan_stage.plan_stage_course_ps.filter(day__gte=now).first()
        end_day = plan_stage.end_day
        now = end_day if plan_stage_course is None else plan_stage_course.day
        if not day:
            day = now if now < end_day else end_day
        plan = plan_stage.plan
        plan_stage_course = plan_stage.plan_stage_course_ps.filter(day=day).first()
        if plan_stage_course is not None:
            mm_PlanJoinInfo.filter(plan_stage_id=plan_stage_id, student_id=user_id).update(plan_stage_course_id=plan_stage_course.id)
        plan_course = {} if plan_stage_course is None else plan_stage_course.plan_course
        plan_clock_in_info = plan_stage.plan_clock_in_info_ps
        res['stage_date'] = json.loads(plan_stage.all_dates) if plan_stage.all_dates else []
        res['start_day'] = plan_stage.start_day
        res['end_day'] = plan_stage.end_day
        res['day'] = day
        res['counter'] = plan_stage.counter
        res['plan_title'] = plan.title
        res['course_title'] = plan_course.title if plan_course else ''
        res['plan_cycle'] = plan.cycle
        res['plan_replenish'] = plan.replenish
        res['clock_in_count'] = plan_clock_in_info.filter(student_id=user_id).count()
        res['replenish_clock_in_num'] = plan_clock_in_info.filter(student_id=user_id, types=mm_PlanClockInInfo.replenish_type).count()
        res['course_content'] = plan_course.content if plan_course else ''
        res['clock_in_date'] = list(plan_clock_in_info.filter(student_id=user_id).values_list('plan_stage_course__day', flat=True))
        clock_in = plan_clock_in_info.filter(student_id=user_id, plan_stage_course__day=day).count()
        if clock_in:
            res['clock_in_status'] = mm_PlanClockInInfo.clock_in_status_already
        else:
            if now == day:
                res['clock_in_status'] = mm_PlanClockInInfo.clock_in_status_now_not
            else:
                res['clock_in_status'] = mm_PlanClockInInfo.clock_in_status_before_not
        res['stage_status'] = mm_PlanStage.stage_status_already if end_day < now else mm_PlanStage.stage_status_running
        res['stage_course_clock_in_count'] = plan_clock_in_info.filter(plan_stage_course__day=day).count()
        return self.success(res)

    def get_task_list(self, request):
        plan_stage_id = request.GET.get('plan_stage_id')
        page = request.GET.get('page')
        day = request.GET.get('day')
        user_id = request.session.get('studentid')
        if day:
            day = datetime.strptime(day, '%Y-%m-%d').date()
        res = {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        if not plan_stage_id:
            return self.success(res)
        plan_stage = mm_PlanStage.get(id=plan_stage_id, plan__status=mm_Plan.on_line_status)
        if plan_stage is None:
            return self.success(res)
        now = date.today()
        end_day = plan_stage.end_day
        if not day:
            day = now if now < end_day else end_day
        res = mm_PlanStage.get_stage_task_list(page=page, plan_stage_id=plan_stage_id, day=day, selfStickie=user_id)
        return self.success(res)

    def get_plan_detail(self, request):
        plan_stage_id = request.GET.get('plan_stage_id')
        user_id = request.session.get('studentid')
        res = {}
        if not plan_stage_id:
            return self.success(res)
        plan_stage = mm_PlanStage.get(id=plan_stage_id, plan__status=mm_Plan.on_line_status)
        if plan_stage is None:
            return self.success(res)
        plan = plan_stage.plan
        res['title'] = plan.title
        res['desc'] = plan.desc
        res['bg_img'] = plan.bg_img
        res['virtual_num'] = plan.virtual_num
        res['original_price'] = plan.original_price
        res['price'] = plan.price
        res['code'] = plan.code
        res['content'] = plan.content
        res['start_day'] = plan_stage.start_day
        res['join_num'] = plan_stage.plan_join_info_ps.count()
        res['join_status'] = mm_PlanJoinInfo.not_join_status if plan_stage.plan_join_info_ps.filter(student_id=user_id).first() is None else mm_PlanJoinInfo.is_join_status
        task_list = mm_PlanStage.get_stage_task_list(page=1, num=10, plan_stage_id=plan_stage_id, refine=mm_PlanClockInInfo.refine_status)
        res['refine_task_list'] = task_list['retlist']
        return self.success(res)

    def get_stage_detail_simplify(self, request):
        plan_stage_id = request.GET.get('plan_stage_id')
        user_id = request.session.get('studentid')
        res = {}
        if not plan_stage_id:
            return self.success(res)
        plan_stage = mm_PlanStage.get(id=plan_stage_id, plan__status=mm_Plan.on_line_status)
        if plan_stage is None:
            return self.success(res)
        plan = plan_stage.plan
        plan_clock_in_info = plan_stage.plan_clock_in_info_ps
        res['stage_date'] = json.loads(plan_stage.all_dates) if plan_stage.all_dates else []
        res['start_day'] = plan_stage.start_day
        res['end_day'] = plan_stage.end_day
        res['counter'] = plan_stage.counter
        res['plan_title'] = plan.title
        res['plan_cycle'] = plan.cycle
        res['plan_replenish'] = plan.replenish
        res['clock_in_count'] = plan_clock_in_info.filter(student_id=user_id).count()
        res['replenish_clock_in_num'] = plan_clock_in_info.filter(student_id=user_id, types=mm_PlanClockInInfo.replenish_type).count()
        res['clock_in_date'] = list(plan_clock_in_info.filter(student_id=user_id).values_list("plan_stage_course__day", flat=True))
        clock_in_date = list(map(str, res['clock_in_date']))
        res['not_clock_in_date'] = list(set(res['stage_date']) - set(clock_in_date))
        res['replenish_clock_in_date'] = list(plan_clock_in_info.filter(student_id=user_id, types=mm_PlanClockInInfo.replenish_type).values_list("plan_stage_course__day", flat=True))
        return self.success(res)

    def get_my_plan_list(self, request):
        page = request.GET.get('page')
        user_id = request.session.get('studentid')
        res = mm_PlanJoinInfo.get_user_list(page=page, num=20, user_id=user_id)
        return self.success(res)

    def get_my_task_list(self, request):
        page = request.GET.get('page')
        plan_stage_id = request.GET.get('plan_stage_id')
        user_id = request.session.get('studentid')
        res = {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        if not plan_stage_id:
            return res
        res = mm_PlanStage.get_stage_task_list(page=page, plan_stage_id=plan_stage_id, user_id=user_id)
        return self.success(res)

    def add_task(self, request):
        content = request.POST.get('content', '')
        imgs = request.POST.get('imgs', '')
        duration = request.POST.get('duration', 0)
        plan_stage_id = request.POST.get('plan_stage_id', 0)
        day = request.POST.get('day')
        if day:
            day = datetime.strptime(day, '%Y-%m-%d').date()
        user_id = request.session.get('studentid')
        result = al_text(content)
        if result == "block":
            return self.error("请文明发布,内容中含有违禁词!")
        userObj = mm_Student.get_or_default(id=user_id)
        if userObj.status in [2, 3]:
            if userObj.status == 3:
                return self.error("发送失败")
            if userObj.status == 2:
                user_status = cache.get('user_status_id'+str(user_id))
                if user_status:
                    return self.error("发送失败")
                else:
                    mm_Student.filter(id=user_id).update(status=1)
        try:
            with transaction.atomic():
                planStage = mm_PlanStage.get(id=plan_stage_id)
                planStageCourse = planStage.plan_stage_course_ps.filter(day=day).first()
                mm_AllData.update_all_num(num=3)
                note = mm_Note.create(content=content, imgs=imgs, student_id=user_id, types=mm_Note.taskType, duration=duration)
                mm_NoteRanking.create(duration=int(duration), student_id=user_id)
                now = date.today()
                types = mm_PlanClockInInfo.normal_type if now == day else mm_PlanClockInInfo.replenish_type
                planClockInInfo = mm_PlanClockInInfo.create(types=types, note_id=note.id, plan_id=planStage.plan_id,
                                          plan_course_id=planStageCourse.plan_course_id, plan_stage_id=planStage.id,
                                          plan_stage_course_id=planStageCourse.id, student_id=user_id)
        except Exception as e:
                print(e)
                return self.error('server error')
        return self.success(planClockInInfo.id)

    def join_plan(self, request):
        plan_stage_id = request.POST.get('plan_stage_id', 0)
        user_id = request.session.get('studentid')
        planStage = mm_PlanStage.get(id=plan_stage_id)
        if planStage is None:
            return self.error("计划不存在，请联系管理员")
        now = date.today()
        joinInfo = mm_PlanJoinInfo.filter(plan__status=mm_Plan.on_line_status, student_id=user_id, plan_stage__start_day__lte=now, plan_stage__end_day__gte=now).first()
        if joinInfo is None:
            planStageCourse = planStage.plan_stage_course_ps.first()
            if planStageCourse is None:
                return self.error("该计划未完善，请联系管理员")
            planJoinInfo = mm_PlanJoinInfo.create(plan_id=planStage.plan_id, plan_stage_id=planStage.id, plan_stage_course_id=planStageCourse.id, student_id=user_id)
            return self.success(planJoinInfo.id)
        else:
            return self.error("已有进行中计划")

    def send_duration(self, request):
        plan_stage_id = request.POST.get('plan_stage_id', 0)
        duration = request.POST.get('duration', 0)
        user_id = request.session.get('studentid')
        planStage = mm_PlanStage.get(id=plan_stage_id)
        if planStage is None:
            return self.error("计划不存在，请联系管理员")
        joinInfo = planStage.plan_join_info_ps.filter(plan__status=mm_Plan.on_line_status, student_id=user_id).first()
        if planStage is None:
            return self.error("未参加该期计划")
        if duration:
            try:
                with transaction.atomic():
                    joinInfo.duration = joinInfo.duration + int(duration)
                    joinInfo.save()
                    mm_NoteRanking.create(duration=int(duration), student_id=user_id)
            except Exception as e:
                print(e)
                return self.error('server error')
        return self.success()

handler = AbsorbedHandler()
